<template>
  <div>
      <el-form ref="login" :model="user" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="user.userName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="user.pwd" placeholder="4-8英文数字字母_注册,字母开头" type="password" autocomplete="off" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="userLogin">登录</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
export default {
  name: 'LoginPage',
  data () {
    return {
      user: {
        userName: '',
        pwd: ''
      },
      rules: {
        userName: [
          {
            required: true,
            message: '用户名必填'
          }
        ],
        pwd: [
          {
            required: true,
            message: '密码必填'
          },
          {
            pattern: /[a-zA-Z]\w{3,7}/,
            message: '4-8英文数字字母_注册,字母开头'
          }
        ]
      }
    }
  },
  methods: {
    userLogin () {
      this.$refs.login.validate().then(() => {
        userLogin(this.user).then(res => {
          if (res.data.code === 200) {
            // 缓存用户个人信息 用于 持久化
            const { token, role, userInfo } = res.data.data
            localStorage.setItem('token', token)
            localStorage.setItem('role', role)
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
            // 存储到vuex
            this.$store.commit('user/INIT_USER', res.data.data)
            this.$message({
              type: 'success',
              message: res.data.msg,
              duration: 2000,
              onClose: () => {
                this.$router.replace('/dashBoard')
              }
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '验证失败'
        })
      })
    },
    resetForm () {

    }
  }
}
</script>

<style lang="scss" scoped></style>
